<script setup lang="ts">
import { ScanLoginConfirmLoginApi } from '@/api/public'
import { showConfirmDialog, showDialog, showToast } from 'vant'

import { useUserStore } from '@/stores/modules/userStore'

const userStore = useUserStore()

const route = useRoute()

const codeInfo = ref()

onMounted(async () => {
  if (!userStore.isComWxEnv) {
    showDialog({
      title: '提示',
      message: '请使用企业微信访问',
    }).then(() => {
      window.close()
    })
    return
  }

  codeInfo.value = route.query.code
  await nextTick()

  if (!codeInfo.value) {
    showDialog({
      title: '提示',
      message: '二维码错误',
    }).then(() => {
      window.close()
    })
    return
  }

  const beforeClose = (action: 'cancel' | 'confirm'): Promise<any> =>
    new Promise(async (resolve) => {
      if (action === 'cancel') {
        window.close()
        resolve(true)
      } else if (action === 'confirm') {
        await ScanLoginConfirmLoginApi({ code: codeInfo.value }).then(() => {
          showToast({ message: '登录成功', duration: 5000 })
          window.close()
          resolve(true)
        })
      }
    })

  showConfirmDialog({
    title: 'pc端扫码登录',
    message: '您确认登录吗？',
    beforeClose,
  })
})
</script>

<template>
  <div></div>
</template>

<style lang="scss" scoped></style>
